package com.zxl.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.mapper.SysMemberMapper;
import com.zxl.common.model.pojo.SysMember;
import com.zxl.common.model.query.member.MemberListQuery;
import com.zxl.common.model.vo.member.MemberListVo;
import com.zxl.common.service.SysMemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 会员信息 服务实现类
 * </p>
 *
 * @author zxw
 * @since 2023-03-30
 */
@Service
public class SysMemberServiceImpl extends ServiceImpl<SysMemberMapper, SysMember> implements SysMemberService {
    @Resource
    private SysMemberMapper sysMemberMapper;

    @Override
    public SysMember chooseHasOpenIdMember(String unionId, String openId) {
        QueryWrapper<SysMember> qw = new QueryWrapper<>();
        if(StrUtil.isNotBlank(unionId) && StrUtil.isNotBlank(openId)) {
            qw.eq("open_id", openId)
                    .or()
                    .eq("union_id", unionId);

        } else if(StrUtil.isNotBlank(openId)) {
            qw.eq("open_id", openId);

        } else if(StrUtil.isNotBlank(unionId)) {
            qw.eq("union_id", unionId);
        } else {
            throw new BusinessException("open_id和union_id参数为空");
        }
        List<SysMember> list = baseMapper.selectList(qw);
        if(list.size() > 0) {
            if(list.size() == 1) {
                return list.get(0);
            }
            for (SysMember member : list) {
                // 返回memberId不为空的用户
                if(StrUtil.isNotBlank(member.getOpenId()) && StrUtil.isNotBlank(member.getUnionId())) {
                    return member;
                } else if(StrUtil.isNotBlank(member.getOpenId())) {
                    return member;
                }
            }
            return list.stream().filter(e -> StrUtil.isNotBlank(e.getUnionId())).min(Comparator.comparing(SysMember::getId)).orElse(null);
        }
        return null;
    }

    @Override
    public List<MemberListVo> selectMemberList(MemberListQuery memberListQuery) {
        PageHelper.startPage(memberListQuery.getPageNumber(),memberListQuery.getPageSize());
        List<MemberListVo> memberListVos = sysMemberMapper.selectMemberList(memberListQuery);
        return memberListVos;
    }
}
